<template>
  <div class="simple-rich-text-editor">
    <!-- 工具栏 -->
    <div class="editor-toolbar" v-if="!readonly">
      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="formatText('bold')" :class="{ active: formats.bold }" title="粗体 (Ctrl+B)">
            <strong>B</strong>
          </el-button>
          <el-button @click="formatText('italic')" :class="{ active: formats.italic }" title="斜体 (Ctrl+I)">
            <em>I</em>
          </el-button>
          <el-button @click="formatText('underline')" :class="{ active: formats.underline }" title="下划线 (Ctrl+U)">
            <u>U</u>
          </el-button>
          <el-button @click="formatText('strikeThrough')" :class="{ active: formats.strike }" title="删除线">
            <s>S</s>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-select v-model="currentHeader" @change="formatHeader" size="small" style="width: 100px">
          <el-option label="正文" :value="false" />
          <el-option label="标题1" :value="1" />
          <el-option label="标题2" :value="2" />
          <el-option label="标题3" :value="3" />
          <el-option label="标题4" :value="4" />
          <el-option label="标题5" :value="5" />
          <el-option label="标题6" :value="6" />
        </el-select>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="formatText('insertUnorderedList')" title="无序列表">
            <el-icon><Operation /></el-icon>
          </el-button>
          <el-button @click="formatText('insertOrderedList')" title="有序列表">
            <el-icon><List /></el-icon>
          </el-button>
          <el-button @click="formatText('outdent')" title="减少缩进">
            <el-icon><Back /></el-icon>
          </el-button>
          <el-button @click="formatText('indent')" title="增加缩进">
            <el-icon><Right /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="formatText('justifyLeft')" title="左对齐">
            <el-icon><AlignLeft /></el-icon>
          </el-button>
          <el-button @click="formatText('justifyCenter')" title="居中对齐">
            <el-icon><AlignCenter /></el-icon>
          </el-button>
          <el-button @click="formatText('justifyRight')" title="右对齐">
            <el-icon><AlignRight /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="insertLink" title="插入链接">
            <el-icon><Link /></el-icon>
          </el-button>
          <el-button @click="insertImage" title="插入图片">
            <el-icon><Picture /></el-icon>
          </el-button>
          <el-button @click="formatText('removeFormat')" title="清除格式">
            <el-icon><Delete /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="undo" :disabled="!canUndo" title="撤销 (Ctrl+Z)">
            <el-icon><RefreshLeft /></el-icon>
          </el-button>
          <el-button @click="redo" :disabled="!canRedo" title="重做 (Ctrl+Y)">
            <el-icon><RefreshRight /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button @click="toggleFullscreen" title="全屏">
          <el-icon><FullScreen /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 编辑器容器 -->
    <div class="editor-container" :class="{ fullscreen: isFullscreen, readonly: readonly }">
      <div 
        ref="editorRef" 
        class="editor-content"
        contenteditable="true"
        :data-placeholder="placeholder"
        @input="handleInput"
        @focus="handleFocus"
        @blur="handleBlur"
        @paste="handlePaste"
        @keydown="handleKeydown"
        @mouseup="updateFormatStates"
        @keyup="updateFormatStates"
        v-html="content"
      ></div>
    </div>

    <!-- 状态栏 -->
    <div class="editor-footer" v-if="showWordCount">
      <div class="word-count">
        <span>字符: {{ wordCount.characters }}</span>
        <span>单词: {{ wordCount.words }}</span>
        <span>段落: {{ wordCount.paragraphs }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// Props定义
interface Props {
  modelValue?: string
  placeholder?: string
  readonly?: boolean
  height?: string | number
  showWordCount?: boolean
  uploadUrl?: string
  uploadHeaders?: Record<string, string>
  maxLength?: number
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '请输入内容...',
  readonly: false,
  height: '400px',
  showWordCount: true,
  uploadUrl: '/api/upload/image',
  uploadHeaders: () => ({}),
  maxLength: 0
})

// Emits定义
interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: string): void
  (e: 'focus'): void
  (e: 'blur'): void
  (e: 'ready'): void
}

const emit = defineEmits<Emits>()

// 响应式数据
const editorRef = ref<HTMLElement>()
const content = ref(props.modelValue)
const isFullscreen = ref(false)
const canUndo = ref(false)
const canRedo = ref(false)
const currentHeader = ref<number | false>(false)

// 格式状态
const formats = reactive({
  bold: false,
  italic: false,
  underline: false,
  strike: false
})

// 计算属性
const wordCount = computed(() => {
  const text = editorRef.value?.textContent || ''
  return {
    characters: text.length,
    words: text.trim() ? text.trim().split(/\s+/).length : 0,
    paragraphs: text.trim() ? text.split(/\n\s*\n/).length : 0
  }
})

// 处理输入
const handleInput = (event: Event) => {
  const target = event.target as HTMLElement
  content.value = target.innerHTML
  emit('update:modelValue', content.value)
  emit('change', content.value)
}

// 处理焦点
const handleFocus = () => {
  emit('focus')
}

// 处理失焦
const handleBlur = () => {
  emit('blur')
}

// 处理粘贴
const handlePaste = (event: ClipboardEvent) => {
  event.preventDefault()
  const text = event.clipboardData?.getData('text/plain') || ''
  document.execCommand('insertText', false, text)
}

// 处理键盘事件
const handleKeydown = (event: KeyboardEvent) => {
  if (event.ctrlKey || event.metaKey) {
    switch (event.key.toLowerCase()) {
      case 'b':
        event.preventDefault()
        formatText('bold')
        break
      case 'i':
        event.preventDefault()
        formatText('italic')
        break
      case 'u':
        event.preventDefault()
        formatText('underline')
        break
      case 'z':
        event.preventDefault()
        undo()
        break
      case 'y':
        event.preventDefault()
        redo()
        break
    }
  }
}

// 格式化文本
const formatText = (command: string, value?: any) => {
  if (!editorRef.value) return

  editorRef.value.focus()
  document.execCommand(command, false, value)
  updateFormatStates()
}

// 格式化标题
const formatHeader = (level: number | false) => {
  if (!editorRef.value) return

  editorRef.value.focus()
  
  if (level === false) {
    document.execCommand('formatBlock', false, 'div')
  } else {
    document.execCommand('formatBlock', false, `h${level}`)
  }
  
  updateFormatStates()
}

// 更新格式状态
const updateFormatStates = () => {
  formats.bold = document.queryCommandState('bold')
  formats.italic = document.queryCommandState('italic')
  formats.underline = document.queryCommandState('underline')
  formats.strike = document.queryCommandState('strikeThrough')
  
  // 检查当前标题级别
  const selection = window.getSelection()
  if (selection && selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    let element = range.commonAncestorContainer
    
    if (element.nodeType === Node.TEXT_NODE) {
      element = element.parentElement
    }
    
    const tagName = (element as Element).tagName
    if (tagName && tagName.match(/^H[1-6]$/)) {
      currentHeader.value = parseInt(tagName.charAt(1))
    } else {
      currentHeader.value = false
    }
  }
}

// 插入链接
const insertLink = () => {
  const url = prompt('请输入链接地址:')
  if (url) {
    const selection = window.getSelection()
    const text = selection && selection.toString() ? selection.toString() : '链接文本'
    document.execCommand('insertHTML', false, `<a href="${url}" target="_blank">${text}</a>`)
  }
  editorRef.value?.focus()
}

// 插入图片
const insertImage = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = async (event: Event) => {
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]
    if (file) {
      // 这里可以实现图片上传逻辑
      const reader = new FileReader()
      reader.onload = (e) => {
        const src = e.target?.result as string
        document.execCommand('insertHTML', false, `<img src="${src}" style="max-width: 100%; height: auto;">`)
        editorRef.value?.focus()
      }
      reader.readAsDataURL(file)
    }
  }
  input.click()
}

// 撤销
const undo = () => {
  document.execCommand('undo')
  editorRef.value?.focus()
}

// 重做
const redo = () => {
  document.execCommand('redo')
  editorRef.value?.focus()
}

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
  
  if (isFullscreen.value) {
    document.body.style.overflow = 'hidden'
  } else {
    document.body.style.overflow = ''
  }
}

// 获取内容
const getContent = () => {
  return content.value
}

// 设置内容
const setContent = (newContent: string) => {
  content.value = newContent
  if (editorRef.value) {
    editorRef.value.innerHTML = newContent
  }
  emit('update:modelValue', content.value)
}

// 聚焦编辑器
const focus = () => {
  editorRef.value?.focus()
}

// 失焦编辑器
const blur = () => {
  editorRef.value?.blur()
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== content.value) {
    content.value = newValue || ''
    if (editorRef.value) {
      editorRef.value.innerHTML = content.value
    }
  }
})

// 生命周期
onMounted(() => {
  nextTick(() => {
    if (editorRef.value) {
      // 设置编辑器高度
      if (typeof props.height === 'number') {
        editorRef.value.style.height = `${props.height}px`
      } else {
        editorRef.value.style.height = props.height
      }

      // 设置只读模式
      if (props.readonly) {
        editorRef.value.contentEditable = 'false'
      }

      emit('ready')
    }
  })
})

onBeforeUnmount(() => {
  if (isFullscreen.value) {
    document.body.style.overflow = ''
  }
})

// 暴露方法给父组件
defineExpose({
  getContent,
  setContent,
  focus,
  blur,
  undo,
  redo,
  toggleFullscreen
})
</script>

<style lang="scss" scoped>
.simple-rich-text-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;

  &.fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    background: #fff;
  }

  .editor-toolbar {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
    padding: 12px;
    border-bottom: 1px solid #e4e7ed;
    background: #f8f9fa;

    .toolbar-group {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-button {
        &.active {
          background: #409eff;
          color: #fff;
          border-color: #409eff;
        }
      }
    }
  }

  .editor-container {
    position: relative;

    &.fullscreen {
      height: calc(100vh - 120px);
    }

    &.readonly {
      .editor-content {
        background: #f5f7fa;
      }
    }

    .editor-content {
      min-height: 400px;
      padding: 16px;
      outline: none;
      line-height: 1.6;
      font-size: 14px;
      overflow-y: auto;

      &[data-placeholder]:empty::before {
        content: attr(data-placeholder);
        color: #c0c4cc;
        font-style: italic;
      }

      &:focus {
        outline: none;
      }

      // 基本样式
      h1, h2, h3, h4, h5, h6 {
        margin: 16px 0 8px 0;
        font-weight: 600;
      }

      p {
        margin: 8px 0;
      }

      ul, ol {
        margin: 8px 0;
        padding-left: 24px;
      }

      li {
        margin: 4px 0;
      }

      a {
        color: #409eff;
        text-decoration: none;

        &:hover {
          text-decoration: underline;
        }
      }

      img {
        max-width: 100%;
        height: auto;
        border-radius: 4px;
        margin: 8px 0;
      }

      blockquote {
        border-left: 4px solid #dfe2e5;
        margin: 16px 0;
        padding: 0 16px;
        color: #6a737d;
      }
    }
  }

  .editor-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    border-top: 1px solid #e4e7ed;
    background: #f8f9fa;
    font-size: 12px;
    color: #909399;

    .word-count {
      display: flex;
      gap: 16px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .simple-rich-text-editor {
    .editor-toolbar {
      padding: 8px;
      gap: 4px;

      .toolbar-group {
        gap: 2px;
      }

      .el-button {
        padding: 4px 8px;
        font-size: 12px;
      }

      .el-select {
        width: 80px !important;
      }
    }
  }
}
</style>
